package com.chender.vm;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.IOException;

import javax.management.RuntimeErrorException;

import org.apache.commons.io.FileUtils;

/**
 * 创建于:2016年8月17日<br>
 * 版权所有(C) 2016 宝润兴业<br>
 * TODO
 * @author chender
 * @version 1.0
 * 
 */
public class Start {
	public static void main(String[] args) {
		File productFolder=new File(args[0]);
		File testFolder=new File(args[1]);
		File file=new File("mergeDesc.txt");
		if(!productFolder.exists()||!testFolder.exists()||!file.exists()){
			throw new RuntimeException("参数不正确");
		}
		FileReader fr=null;
		BufferedReader br=null;
		try{
			fr=new FileReader(file);
			br=new BufferedReader(fr);
			String line=null;
			while((line=br.readLine())!=null){
				if("".equals(line.trim())){
					System.out.println("skip...");
					continue;
				}
				line=line.replace("/", File.separator).replace("\\", File.separator);
				if(line.contains("../")){
					throw new RuntimeException("非法路径:"+line);
				}
				if(!line.startsWith(File.separator)){
					line=File.separator+line;
				}
				File pFile=new File(productFolder,line);
				File tFile=new File(testFolder,line);
				if(!pFile.exists()){
					throw new RuntimeException("文件不存在:"+pFile.getAbsolutePath());
				}
				if(tFile.exists()){
					tFile.delete();
				}
				tFile.getParentFile().mkdirs();
				mergeFile(pFile,tFile);
				System.out.println(line);
			}
		}catch(Exception e){
			throw new RuntimeException("合并失败",e);
		}finally{
			if(br!=null){
				try {
					br.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		
	}
	
	private static void mergeFile(File pFile,File tFile){
		if(pFile.isFile()){
			try {
				FileUtils.copyFile(pFile, tFile);
			} catch (Exception e) {
				throw new RuntimeException("移动文件失败:"+pFile.getAbsolutePath(),e);
			}
		}else{
			File[] files=pFile.listFiles();
			if(files!=null&&files.length!=0){
				for (File file : files) {
					mergeFile(file,new File(tFile,file.getName()));
				}
			}
		}
	}
}
